/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.cef.core.rootmanager;

import com.inspur.edp.cef.api.dataType.entity.ICefRootEntity;
import com.inspur.edp.cef.api.rootManager.ICefRootManager;
import com.inspur.edp.cef.api.rootManager.IRootEntityCacheManager;
import com.inspur.edp.cef.api.session.ICefSession;
import com.inspur.edp.cef.api.session.ICefSessionItem;
import com.inspur.edp.cef.entity.dependenceTemp.DataValidator;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class BaseRootEntityCacheManager implements IRootEntityCacheManager
{

		///#region 字段
	private cefReadWriteLock rwl;
	private java.util.Map<String, ICefRootEntity> rootEntities;
	private String entityType;
	protected ICefRootManager rootMgr;
	private ICefSession session;

	protected BaseRootEntityCacheManager(String entityType, ICefRootManager rootMgr, ICefSession session) {
		DataValidator.checkForEmptyString(entityType, "entityType");
		//DataValidator.checkForNullReference(session, "session");
		//DataValidator.checkForNullReference(rootMgr, "rootMgr");

		this.entityType = entityType;
		this.rootMgr = rootMgr;
		this.session = session;
	}

	private cefReadWriteLock readerWriterLockSlim()
	{
		if(rwl==null)
			rwl=new cefReadWriteLock();
		return rwl;
		}

	protected java.util.Map<String, ICefRootEntity> getDicBE()
	{
		if (rootEntities != null)
		{
			return rootEntities;
		}
		ICefSessionItem sessionItem= session.getSessionItems().get(entityType);
		if(sessionItem==null)
		{
			throw new RuntimeException();
		}
		rootEntities = sessionItem.getRootEntities();
		return rootEntities;
	}

	public final ICefRootEntity getEntity(String dataId)
	{
		return getEntityWithLock(dataId);
	}

	@Deprecated
	public final java.util.ArrayList<ICefRootEntity> getEntities(java.util.ArrayList<String> ids)
	{
		Objects.requireNonNull(ids, "ids");
		java.util.ArrayList<ICefRootEntity> list = new java.util.ArrayList<ICefRootEntity>(ids.size());
		for (String id : ids)
		{
			list.add(getEntityWithLock(id));
		}
		return list;
	}

	public final Map<String, ICefRootEntity> getEntities(List<String> ids)
	{
		Objects.requireNonNull(ids, "ids");
		HashMap<String, ICefRootEntity> result = new HashMap<>(ids.size());
		for (String id : ids) {
			result.put(id, getEntityWithLock(id));
		}
		return result;
	}

	public final java.util.ArrayList<ICefRootEntity> getAllEntities() {
		readerWriterLockSlim().enterUpgradeableReadLock();
		try {
			return new java.util.ArrayList<ICefRootEntity>(getDicBE().values());
		} finally {
			readerWriterLockSlim().exitUpgradeableReadLock();
		}
	}

	public final void clearEntities()
	{
		readerWriterLockSlim().enterWriteLock();
		try
		{
			getDicBE().clear();
		}
		finally
		{
			readerWriterLockSlim().exitWriteLock();
		}
	}

	private ICefRootEntity getEntityWithLock(String dataId)
	{
		//①加读锁，第一次读取；
		readerWriterLockSlim().enterUpgradeableReadLock();
		try
		{
			ICefRootEntity be = innerGetEntity(dataId);
			if (be == null)
			{
				//②未获取到，提升为写锁，第二次读取；
				readerWriterLockSlim().enterWriteLock();
				try
				{
					be = innerGetEntity(dataId);
					if (be == null)
					{
						//③未获取到，初始化实体，新增至BEFunSession的实体字典；
						be = createNewEntity(dataId);
						addEntity(dataId, be);
					}
				}
				finally
				{
					readerWriterLockSlim().exitWriteLock();
				}

			}
			return be;
		}
		finally
		{
			if (readerWriterLockSlim().isUpgradeableReadLockHeld())
			{
				readerWriterLockSlim().exitUpgradeableReadLock();
			}
		}
	}

	private ICefRootEntity createNewEntity(String id)
	{
		return rootMgr.createEntity(id);
	}

	private ICefRootEntity innerGetEntity(String id)
	{
		ICefRootEntity be = getDicBE().get(id);
		return be;
	}

	private void addEntity(String id, ICefRootEntity be)
	{
		getDicBE().put(id, be);
	}

	public void deleteEntity(String entityId)
	{
		getDicBE().remove(entityId);
	}
}
